"""Setup the papyrus application"""
import os
import logging

import pylons.test
from ConfigParser import SafeConfigParser
from sqlalchemy.util import OrderedDict
from getpass import getpass

from papyrus.config.environment import load_environment
from papyrus.model import meta
from papyrus.model.auth import User

log = logging.getLogger(__name__)


def make_admin(name, email, password):
    user = User()
    user.name = name
    user.email = email
    user.password = password
    user.is_admin = True
    user.confirmed = True
    return user


def setup_app(command, conf, vars):
    """Place any commands to setup papyrus here"""

    # Check if papyrus.ini exists
    papyrus_ini = conf['papyrus.ini']
    if not os.path.exists(papyrus_ini):
        # Create a new configuration
        papyrus_conf = SafeConfigParser(None, OrderedDict)

        papyrus_conf.add_section(u"general")
        papyrus_conf.set(u"general", u"blog_title", u"Your blog's title")
        papyrus_conf.set(u"general", u"blog_tag", u"Your blog's tag")
        papyrus_conf.set(u"general", u"blog_description", u"A not too long description of your blog.")
        papyrus_conf.set(u"general", u"blog_keywords", u"some,comma,separated,keywords")
        papyrus_conf.set(u"general", u"posts_per_page", u"10")
        papyrus_conf.set(u"general", u"blog_copyright", u"Some copyright.")

        papyrus_conf.add_section(u"widgets")
        papyrus_conf.set(u"widgets", u"widgets_twitter", u"")

        with open(papyrus_ini, "w") as f:
            papyrus_conf.write(f)

    # Don't reload the app if it was loaded under the testing environment
    if pylons.test.pylonsapp:
        return

    load_environment(conf.global_conf, conf.local_conf)

    # Create the tables if they don't already exist
    meta.metadata.create_all(bind=meta.engine)

    # Make sure admin hasn't been setup yet
    user = meta.Session.query(User).first()
    if user:
        return

    # Setup
    name = u"%s" % raw_input("Name: ")
    email = u"%s" % raw_input("Email: ")
    password = u"%s" % getpass("Password: ")
    assert password == u"%s" % getpass("Confirm: "), "Password mismatch"

    user = make_admin(name, email, password)

    meta.Session.add(user)
    meta.Session.commit()
